package com.ellfors.common.ext

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import com.ellfors.common.app.MyApp
import java.util.Timer
import java.util.TimerTask

fun EditText.showKeyboard() {
    isFocusable = true
    isFocusableInTouchMode = true
    requestFocus()
    val timer = Timer()
    timer.schedule(object : TimerTask() {
        override fun run() {
            val inputManager =
                MyApp.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.showSoftInput(this@showKeyboard, 0)
        }
    }, 500)
}

fun Activity.hideKeyboard() {
    try {
        val view: View? = currentFocus
        if (view != null) {
            val inputManager: InputMethodManager =
                getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.hideSoftInputFromWindow(
                view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

fun View.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    if (imm.isActive) {
        imm.hideSoftInputFromWindow(applicationWindowToken, 0)
    }
}